const { sequelize, testConnection } = require('../dao/dbConnect');
const { 
  User, 
  Course, 
  CourseCategory, 
  EvaluationRecord, 
  GameRecord, 
  DailyRecord 
} = require('../dao/model');

/**
 * 数据库种子数据管理器
 */
class SeederManager {
  constructor() {
    this.seeders = [
      { name: 'categories', fn: this.seedCategories.bind(this) },
      { name: 'admin', fn: this.seedAdminUser.bind(this) },
      { name: 'courses', fn: this.seedCourses.bind(this) },
      { name: 'demo-users', fn: this.seedDemoUsers.bind(this) },
      { name: 'demo-records', fn: this.seedDemoRecords.bind(this) }
    ];
  }

  /**
   * 插入课程分类数据
   */
  async seedCategories() {
    console.log('📚 插入课程分类数据...');
    
    const categories = [
      { name: '基础发音', description: '学习普通话基础发音技巧', parent_id: null, sort_order: 1 },
      { name: '声母练习', description: '声母发音专项练习', parent_id: 1, sort_order: 1 },
      { name: '韵母练习', description: '韵母发音专项练习', parent_id: 1, sort_order: 2 },
      { name: '声调练习', description: '四声调发音练习', parent_id: 1, sort_order: 3 },
      { name: '词汇朗读', description: '常用词汇朗读练习', parent_id: null, sort_order: 2 },
      { name: '日常用语', description: '日常生活用语练习', parent_id: 5, sort_order: 1 },
      { name: '商务用语', description: '商务场景用语练习', parent_id: 5, sort_order: 2 },
      { name: '文章朗读', description: '文章段落朗读练习', parent_id: null, sort_order: 3 },
      { name: '诗词朗诵', description: '古诗词朗诵练习', parent_id: 8, sort_order: 1 },
      { name: '散文朗读', description: '散文作品朗读练习', parent_id: 8, sort_order: 2 }
    ];

    const existingCount = await CourseCategory.count();
    if (existingCount > 0) {
      console.log('⚠️  分类数据已存在，跳过插入');
      return;
    }

    await CourseCategory.bulkCreate(categories);
    console.log(`✅ 成功插入 ${categories.length} 个分类`);
  }

  /**
   * 创建管理员用户
   */
  async seedAdminUser() {
    console.log('👤 创建管理员用户...');
    
    const adminData = {
      username: 'admin',
      password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
      nickname: '系统管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      role: 'admin',
      status: 'active',
      avatar: 'https://example.com/images/admin-avatar.jpg',
      level: 10,
      experience: 10000,
      total_study_time: 0,
      points: 0
    };

    const existingAdmin = await User.findOne({ where: { username: 'admin' } });
    if (existingAdmin) {
      console.log('⚠️  管理员用户已存在，跳过创建');
      return;
    }

    await User.create(adminData);
    console.log('✅ 管理员用户创建成功');
    console.log('📝 登录信息: 用户名=admin, 密码=password');
  }

  /**
   * 插入课程数据
   */
  async seedCourses() {
    console.log('📖 插入课程数据...');
    
    const courses = [
      {
        title: '普通话基础入门',
        description: '从零开始学习普通话，掌握基本发音规则',
        category_id: 1,
        difficulty: 'beginner',
        is_free: true,
        price: 0,
        cover_image: 'https://example.com/images/course1.jpg',
        content: '本课程将带您从最基础的声母、韵母开始学习普通话，通过系统的练习帮助您掌握标准的普通话发音。',
        duration: 1800,
        views: 1250,
        likes: 89,
        enrollments: 456,
        is_published: true,
        published_at: new Date()
      },
      {
        title: '声母发音技巧',
        description: '详细讲解21个声母的正确发音方法',
        category_id: 2,
        difficulty: 'beginner',
        is_free: true,
        price: 0,
        cover_image: 'https://example.com/images/course2.jpg',
        content: '声母是普通话发音的基础，本课程将逐一讲解每个声母的发音要领和常见错误。',
        duration: 2400,
        views: 980,
        likes: 67,
        enrollments: 234,
        is_published: true,
        published_at: new Date()
      },
      {
        title: '韵母发音精讲',
        description: '掌握39个韵母的发音要领和练习方法',
        category_id: 3,
        difficulty: 'intermediate',
        is_free: false,
        price: 29.9,
        cover_image: 'https://example.com/images/course3.jpg',
        content: '韵母发音是普通话学习的重点和难点，本课程提供详细的发音指导和练习方法。',
        duration: 3600,
        views: 756,
        likes: 45,
        enrollments: 123,
        is_published: true,
        published_at: new Date()
      },
      {
        title: '四声调练习',
        description: '学会正确掌握普通话的四个声调',
        category_id: 4,
        difficulty: 'intermediate',
        is_free: false,
        price: 19.9,
        cover_image: 'https://example.com/images/course4.jpg',
        content: '声调是普通话的重要组成部分，直接影响语义表达，本课程帮您掌握标准声调。',
        duration: 2700,
        views: 634,
        likes: 38,
        enrollments: 89,
        is_published: true,
        published_at: new Date()
      },
      {
        title: '日常用语实战',
        description: '学习日常生活中常用的普通话表达',
        category_id: 6,
        difficulty: 'beginner',
        is_free: true,
        price: 0,
        cover_image: 'https://example.com/images/course5.jpg',
        content: '通过实际场景学习日常用语的正确表达，提高普通话的实用性。',
        duration: 2100,
        views: 1456,
        likes: 112,
        enrollments: 567,
        is_published: true,
        published_at: new Date()
      }
    ];

    const existingCount = await Course.count();
    if (existingCount > 0) {
      console.log('⚠️  课程数据已存在，跳过插入');
      return;
    }

    await Course.bulkCreate(courses);
    console.log(`✅ 成功插入 ${courses.length} 个课程`);
  }

  /**
   * 创建演示用户
   */
  async seedDemoUsers() {
    console.log('👥 创建演示用户...');
    
    const demoUsers = [
      {
        username: 'teacher01',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        nickname: '张老师',
        email: 'teacher01@example.com',
        phone: '13800138001',
        role: 'teacher',
        status: 'active',
        level: 8,
        experience: 5000,
        total_study_time: 36000,
        points: 2500
      },
      {
        username: 'student01',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        nickname: '小明',
        email: 'student01@example.com',
        phone: '13800138002',
        role: 'user',
        status: 'active',
        level: 3,
        experience: 1200,
        total_study_time: 7200,
        points: 800
      },
      {
        username: 'student02',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        nickname: '小红',
        email: 'student02@example.com',
        phone: '13800138003',
        role: 'user',
        status: 'active',
        level: 5,
        experience: 2800,
        total_study_time: 14400,
        points: 1500
      }
    ];

    // 检查是否已有演示用户
    const existingDemo = await User.findOne({ where: { username: 'teacher01' } });
    if (existingDemo) {
      console.log('⚠️  演示用户已存在，跳过创建');
      return;
    }

    await User.bulkCreate(demoUsers);
    console.log(`✅ 成功创建 ${demoUsers.length} 个演示用户`);
    console.log('📝 演示账号: teacher01/student01/student02, 密码均为: password');
  }

  /**
   * 创建演示记录数据
   */
  async seedDemoRecords() {
    console.log('📊 创建演示记录数据...');
    
    // 获取用户ID
    const student01 = await User.findOne({ where: { username: 'student01' } });
    const student02 = await User.findOne({ where: { username: 'student02' } });
    
    if (!student01 || !student02) {
      console.log('⚠️  演示用户不存在，跳过创建记录');
      return;
    }

    // 检查是否已有记录
    const existingRecords = await EvaluationRecord.count();
    if (existingRecords > 0) {
      console.log('⚠️  演示记录已存在，跳过创建');
      return;
    }

    // 创建评测记录
    const evaluationRecords = [
      {
        user_id: student01.id,
        text_content: '我爱学习普通话',
        score: 85.5,
        accuracy: 88.0,
        fluency: 82.0,
        completeness: 87.0,
        suggestions: ['注意声调的准确性', '语速可以稍微放慢'],
        detail_scores: [
          { word: '我', score: 90, issues: [] },
          { word: '爱', score: 85, issues: ['声调偏低'] },
          { word: '学', score: 88, issues: [] },
          { word: '习', score: 82, issues: ['发音不够清晰'] },
          { word: '普', score: 90, issues: [] },
          { word: '通', score: 85, issues: [] },
          { word: '话', score: 87, issues: [] }
        ],
        duration: 3
      },
      {
        user_id: student02.id,
        text_content: '今天天气真好',
        score: 92.0,
        accuracy: 94.0,
        fluency: 90.0,
        completeness: 92.0,
        suggestions: ['发音清晰，继续保持'],
        detail_scores: [
          { word: '今', score: 95, issues: [] },
          { word: '天', score: 92, issues: [] },
          { word: '天', score: 90, issues: [] },
          { word: '气', score: 88, issues: ['轻声处理'] },
          { word: '真', score: 94, issues: [] },
          { word: '好', score: 93, issues: [] }
        ],
        duration: 2
      }
    ];

    await EvaluationRecord.bulkCreate(evaluationRecords);

    // 创建游戏记录
    const gameRecords = [
      {
        user_id: student01.id,
        game_type: 'pronunciation',
        target_word: '中国',
        user_pronunciation: 'zhōng guó',
        score: 88.0,
        similarity: 92.0,
        duration: 2
      },
      {
        user_id: student02.id,
        game_type: 'pronunciation',
        target_word: '学习',
        user_pronunciation: 'xué xí',
        score: 95.0,
        similarity: 98.0,
        duration: 1
      }
    ];

    await GameRecord.bulkCreate(gameRecords);

    // 创建每日记录
    const dailyRecords = [
      {
        user_id: student01.id,
        date: new Date().toISOString().split('T')[0],
        content: '春眠不觉晓，处处闻啼鸟。',
        score: 87.5,
        duration: 5
      },
      {
        user_id: student02.id,
        date: new Date().toISOString().split('T')[0],
        content: '床前明月光，疑是地上霜。',
        score: 91.0,
        duration: 4
      }
    ];

    await DailyRecord.bulkCreate(dailyRecords);

    console.log('✅ 演示记录数据创建成功');
  }

  /**
   * 执行所有种子数据插入
   */
  async seed(seedNames = null) {
    console.log('🌱 开始插入种子数据...');
    console.log('='.repeat(50));

    try {
      await testConnection();

      const seedersToRun = seedNames 
        ? this.seeders.filter(s => seedNames.includes(s.name))
        : this.seeders;

      if (seedersToRun.length === 0) {
        console.log('⚠️  没有找到指定的种子数据');
        return;
      }

      for (const seeder of seedersToRun) {
        await seeder.fn();
      }

      console.log('='.repeat(50));
      console.log('🎉 种子数据插入完成！');
      console.log('📊 数据统计:');
      console.log(`   分类数量: ${await CourseCategory.count()}`);
      console.log(`   课程数量: ${await Course.count()}`);
      console.log(`   用户数量: ${await User.count()}`);
      console.log(`   评测记录: ${await EvaluationRecord.count()}`);
      console.log(`   游戏记录: ${await GameRecord.count()}`);
      console.log(`   每日记录: ${await DailyRecord.count()}`);

    } catch (error) {
      console.error('💥 种子数据插入失败:', error);
      throw error;
    }
  }

  /**
   * 清空所有数据
   */
  async reset() {
    console.log('🗑️  开始清空数据...');
    
    try {
      await DailyRecord.destroy({ where: {}, force: true });
      await GameRecord.destroy({ where: {}, force: true });
      await EvaluationRecord.destroy({ where: {}, force: true });
      await Course.destroy({ where: {}, force: true });
      await CourseCategory.destroy({ where: {}, force: true });
      await User.destroy({ where: {}, force: true });
      
      console.log('✅ 数据清空完成');
    } catch (error) {
      console.error('❌ 数据清空失败:', error);
      throw error;
    }
  }
}

/**
 * 命令行处理
 */
async function main() {
  const seeder = new SeederManager();
  const command = process.argv[2] || 'seed';
  const seedNames = process.argv.slice(3);

  try {
    switch (command) {
      case 'seed':
        await seeder.seed(seedNames.length > 0 ? seedNames : null);
        break;
      
      case 'reset':
        await seeder.reset();
        break;
      
      case 'refresh':
        await seeder.reset();
        await seeder.seed();
        break;
      
      default:
        console.log('用法:');
        console.log('  node seed.js seed [names...]  # 插入种子数据');
        console.log('  node seed.js reset           # 清空所有数据');
        console.log('  node seed.js refresh         # 清空并重新插入数据');
        console.log('');
        console.log('可用的种子数据:');
        console.log('  categories, admin, courses, demo-users, demo-records');
        process.exit(1);
    }

  } catch (error) {
    console.error('💥 操作失败:', error.message);
    process.exit(1);
  } finally {
    await sequelize.close();
    console.log('🔌 数据库连接已关闭');
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = SeederManager;
